package com.hyfd.service.mp;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.github.pagehelper.PageHelper;
import com.hyfd.common.BaseJson;
import com.hyfd.common.ExcelUtil;
import com.hyfd.common.GlobalSetHyfd;
import com.hyfd.common.Page;
import com.hyfd.dao.mp.BillPkgDao;
import com.hyfd.dao.mp.ProviderBillDiscountDao;
import com.hyfd.dao.mp.ProviderPhysicalChannelDao;
import com.hyfd.service.BaseService;

@Service
@Transactional
public class ProviderBillDiscountSer extends BaseService{
	
	public Logger log = Logger.getLogger(this.getClass());
	
	@Autowired
	BillPkgDao billPkgDao;
	
	@Autowired
	ProviderBillDiscountDao providerBillDiscountDao;
	@Autowired
	ProviderPhysicalChannelDao providerPhysicalChannelDao;
	
	public String providerBillDiscountEditPage(HttpServletRequest req,String id){
		try{
			Map<String, Object> m=providerPhysicalChannelDao.getProviderPhysicalChannelById(id);
			req.setAttribute("providerPhysicalChannel", m);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return "mp/providerBillDiscountEdit";
	}

	public String getProviderBillDiscountByBillPkgId(String bill_pkg_id){
		StringBuilder sb=new StringBuilder();
		try{
			List<Map<String, Object>> billList=providerBillDiscountDao.getProviderBillDiscountByBillPkgId(bill_pkg_id);
			String billListJson=BaseJson.listToJson(billList);
			sb.append(billListJson);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return sb.toString();
		
	}
	
	public String getProviderBillDiscountByBillPkgIdAndProvinceCode(HttpServletRequest req){
		StringBuilder sb=new StringBuilder();
		try{
			Map<String, Object> reqParMap=getMaps(req);
			List<Map<String, Object>> billList=providerBillDiscountDao.getProviderBillDiscountByBillPkgIdAndProvinceCode(reqParMap);
			String billListJson=BaseJson.listToJson(billList);
			sb.append(billListJson);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return sb.toString();
	}
	
	public String providerBillDiscountAdd(HttpServletRequest req){
		boolean flag=false;
		try{
		Map<String, Object> myBill=getMaps(req);
		
		Map<String, Object> userInfoMap=getUser(); //取到当前用户信息
		
		myBill.put("create_user", userInfoMap.get("suId"));//放入创建用户
		
		int rows=providerBillDiscountDao.providerBillDiscountAdd(myBill);
		if(rows>0){
			flag=true;
		}
		}catch(Exception e){
			getMyLog(e,log);
		}
		return flag+"";		
	}
	
	public String providerBillDiscountEdit(HttpServletRequest req,String id){
		boolean flag=false;
		try{
		Map<String, Object> myBill=getMaps(req);
		
		Map<String, Object> userInfoMap=getUser(); //取到当前用户信息
		
		myBill.put("update_user", userInfoMap.get("suId"));//放入创建用户
		int rows=providerBillDiscountDao.providerBillDiscountEdit(myBill);
		if(rows>0){
			flag=true;
		}
		}catch(Exception e){
			getMyLog(e,log);
		}
		return flag+"";	
	}
	
	public String providerBillDiscountUpload(HttpServletRequest req){
		String result="";
		try{
			Map<String, Object> userInfoMap=getUser(); //取到当前用户信息
			
			String provider_id=req.getParameter("provider_id");
			String bill_pkg_id=req.getParameter("bill_pkg_id");
			String discountType=req.getParameter("discountType");
			
			String resultFileName="";
			String savePath=getMyAppPath(req)+GlobalSetHyfd.savePath;
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy_MM_dd");
			savePath=savePath+"/"+sdf.format(new Date());
			
			createDir(savePath);
			//---------------------------------文件上传开始
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(req.getServletContext());
			if(multipartResolver.isMultipart(req)){
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)req; 
				Iterator<String> iter = multiRequest.getFileNames();
				 while(iter.hasNext()){
					 MultipartFile file = multiRequest.getFile(iter.next());  
		              if(file != null){
		            	  String myFileName = file.getOriginalFilename();
		            	  myFileName=Calendar.getInstance().getTimeInMillis()+myFileName.substring(myFileName.lastIndexOf("."),myFileName.length());
		            	  myFileName=savePath+"/"+myFileName;
		            	  resultFileName=myFileName;
		            	  File myLocalFile=new File(myFileName);
		            	  file.transferTo(myLocalFile);
		              }
				 }
			}
			//------------------------------文件上传结束
			//删除所有折扣数据
			providerBillDiscountDao.deleteProviderBillDiscountByBillPkgId(bill_pkg_id);
			//------------------------------读取excel文件开始
			Map<String, List<String[]>> mapBill=ExcelUtil.readExcel(resultFileName);
			Set<Entry<String, List<String[]>>> setBill= mapBill.entrySet();
			for(Map.Entry<String, List<String[]>> entry:setBill){
//				String sheetName=entry.getKey();
				List<String[]> sheetData=entry.getValue();
				int rowIndex=0;
				for(String[] col:sheetData){
					if(rowIndex==0){
						rowIndex++;
						continue; // 不读第一行
					}
					Map<String, Object> providerBillDiscountMap=new HashMap<String, Object>();
					providerBillDiscountMap.put("provider_id", provider_id);
					providerBillDiscountMap.put("bill_pkg_id", bill_pkg_id);
					
					providerBillDiscountMap.put("province_code", col[0]);
					if("1".equals(discountType)){
					providerBillDiscountMap.put("discount", col[1]);
					}else if("2".equals(discountType)){
						providerBillDiscountMap.put("city_code", col[1]);
						providerBillDiscountMap.put("discount", col[2]);	
					}
					
					
					providerBillDiscountMap.put("create_user", userInfoMap.get("suId"));
					//将折扣数据导入数据库
					providerBillDiscountDao.providerBillDiscountAdd(providerBillDiscountMap);
					rowIndex++;
				}
			}
			//------------------------------读取excel文件结束
			
		result="true";
		}catch(Exception e){
			getMyLog(e,log);
			result=e.getMessage();
		}
		return result+"";	
	}
	
	/**
	 * 获取记录数量
	 * @param m
	 * @return
	 */
	public int getAgentCount(Map<String, Object> m){
		int agentCount=0;
		try{
			agentCount=providerBillDiscountDao.selectCount(m);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return agentCount;
	}
	
	/**
	 * <h5>功能描述:</h5>	跳转到运营商折扣包折扣页面
	 *
	 * @param req
	 * @return
	 *
	 * @作者：zhangpj		@创建时间：2017年5月30日
	 */
	public String providerBillDiscountListPage(String id,HttpServletRequest req){
		Map<String, Object> providerPhysicalChannel = providerPhysicalChannelDao.selectByPrimaryKey(id);
		req.setAttribute("providerPhysicalChannel", providerPhysicalChannel);
		return "mp/providerBillDiscountList";
	}
	
	/**
	 * <h5>功能描述:</h5>	分页获取运营商物理通道折扣信息
	 *
	 * @param req
	 * @return
	 *
	 * @作者：zhangpj		@创建时间：2017年5月10日
	 */
	public String providerBillDiscountList(HttpServletRequest req){
		StringBuilder sb = new StringBuilder();
		try {
			Map<String, Object> m = getMaps(req); // 封装前台参数为map
			Page p = getPage(m);// 提取分页参数
			int total = getAgentCount(m);
			p.setCount(total);
			int pageNum = p.getCurrentPage();
			int pageSize = p.getPageSize();

			sb.append("{");
			sb.append("" + getKey("page") + ":" + p.getCurrentPage() + ",");
			sb.append("" + getKey("total") + ":" + p.getNumCount() + ",");
			sb.append("" + getKey("records") + ":" + p.getCount() + ",");
			sb.append("" + getKey("rows") + ":" + "");

			PageHelper.startPage(pageNum, pageSize);// mybatis分页插件
			List<Map<String, Object>> dataList = providerBillDiscountDao.selectAll(m);
			String dataListJson = BaseJson.listToJson(dataList);
			sb.append(dataListJson);
			sb.append("}");
		} catch (Exception e) {
			getMyLog(e, log);
		}
		
		return sb.toString();
	}

	/**
	 * @功能描述：	设置物理运营商通道话费折扣
	 *
	 * @作者：zhangpj		@创建时间：2017年5月15日
	 * @param req
	 * @return
	 */
	public String providerBillDiscountEditExt(HttpServletRequest req){
		boolean flag=true;
		try{
			Map<String, Object> myData=getMaps(req);
			Map<String, Object> userInfoMap=getUser(); //取到当前用户信息
			
			myData.put("createUser", userInfoMap.get("suId"));//放入创建用户
			String[] billPkgDiscount  = myData.get("billPkgDiscount").toString().split(",");
			
			// 删除指定流量包折扣旧数据
			providerBillDiscountDao.deleteProviderBillDiscount(myData);
			
			for (int i = 0; i < billPkgDiscount.length; i++) {
				String[] discountInfo = billPkgDiscount[i].split("-");
				myData.put("name", discountInfo[0]);
				myData.put("billPkgId", discountInfo[1]);
				myData.put("discount", discountInfo[2]);
				
				// 添加运营商流量折扣信息
				int rows=providerBillDiscountDao.providerBillDiscountAdd(myData);
				if(rows < 1){
					flag = false;
					throw new Exception("插入话费包折扣异常");
				}
			}
		}catch(Exception e){
			getMyLog(e,log);
		}
		return flag+"";		
	}
	
	/**
	 * @功能描述：	折扣设置页面获取满足条件的话费包折扣信息
	 *
	 * @作者：zhangpj		@创建时间：2017年5月16日
	 * @param req
	 * @return
	 */
	public String selectProviderBillDiscount(HttpServletRequest req){
		StringBuilder sb=new StringBuilder();
		try{
			Map<String, Object> maps = getMaps(req);
			List<Map<String, Object>> dataList=providerBillDiscountDao.selectAll(maps);
			String dataListJson=BaseJson.listToJson(dataList);
			sb.append(dataListJson);
		}catch(Exception e){
			getMyLog(e,log);
		}
		return sb.toString();
	}
}
